#!/bin/bash

# 检查.env文件是否存在
if [ ! -f ".env" ]; then
    echo "错误: 未找到 .env 文件"
    echo "请确保 .env 文件存在并包含必要的环境变量"
    exit 1
fi

# 从.env文件加载环境变量
source .env

# 检查必要的环境变量
if [ -z "$OPENAI_API_KEY" ]; then
    echo "错误: OPENAI_API_KEY 未设置"
    exit 1
fi

echo "使用以下配置启动本地容器:"
echo "OPENAI_API_KEY: ${OPENAI_API_KEY:0:10}..."
echo "OPENAI_BASE_URL: $OPENAI_BASE_URL"
echo "MODEL_NAME: $MODEL_NAME"
echo "MAX_TOKENS: $MAX_TOKENS"

# 检查是否设置了Python源
if [ -n "$PIP_INDEX_URL" ]; then
    echo "PIP_INDEX_URL: $PIP_INDEX_URL"
    if [ -n "$PIP_TRUSTED_HOST" ]; then
        echo "PIP_TRUSTED_HOST: $PIP_TRUSTED_HOST"
    fi
else
    echo "PIP_INDEX_URL: 官方源（默认）"
fi
echo ""

# 停止并删除已存在的容器
docker stop chatbot 2>/dev/null || true
docker rm chatbot 2>/dev/null || true

# 检查是否需要显示实时日志
if [ "$1" = "--logs" ] || [ "$1" = "-l" ]; then
    echo "启动容器并显示实时日志..."
    # 交互式启动，显示实时日志
    docker run --name chatbot \
        --rm \
        -p 127.0.0.1:8000:8000 \
        -e OPENAI_API_KEY="$OPENAI_API_KEY" \
        -e OPENAI_BASE_URL="$OPENAI_BASE_URL" \
        -e MODEL_NAME="$MODEL_NAME" \
        -e MAX_TOKENS="$MAX_TOKENS" \
        -e PIP_INDEX_URL="$PIP_INDEX_URL" \
        -e PIP_TRUSTED_HOST="$PIP_TRUSTED_HOST" \
        chatbot:latest
else
    # 后台启动
    docker run --name chatbot \
        -d \
        -p 127.0.0.1:8000:8000 \
        -e OPENAI_API_KEY="$OPENAI_API_KEY" \
        -e OPENAI_BASE_URL="$OPENAI_BASE_URL" \
        -e MODEL_NAME="$MODEL_NAME" \
        -e MAX_TOKENS="$MAX_TOKENS" \
        -e PIP_INDEX_URL="$PIP_INDEX_URL" \
        -e PIP_TRUSTED_HOST="$PIP_TRUSTED_HOST" \
        chatbot:latest 

    if [ $? -eq 0 ]; then
        echo "本地容器启动成功!"
        echo "访问地址: http://127.0.0.1:8000"
        echo "查看实时日志: docker logs -f chatbot"
        echo "显示启动日志: ./scripts/docker-run-local.sh --logs"
        echo ""
        echo "注意: 此容器仅允许本地访问 (127.0.0.1)"
        
        # 显示前几行日志以确认启动状态
        echo ""
        echo "=== 启动日志预览 ==="
        sleep 2
        docker logs chatbot | head -20
    else
        echo "容器启动失败!"
        exit 1
    fi
fi

